import os
import subprocess
import ntplib
import subprocess
import time
import datetime


NTP_SERVERS = [
    'pool.ntp.org',
    'time.nist.gov',
    'cn.pool.ntp.org',  # 中国NTP服务器
    '1.cn.pool.ntp.org',
    '2.cn.pool.ntp.org',
    '120.25.115.20',    # 阿里云NTP
    '182.92.12.11'      # 腾讯云NTP
]
def sync_time_with_ntp(ntp_server='pool.ntp.org'):
    """
    同步本地时间到指定的 NTP 服务器。
    :param ntp_server: NTP 服务器地址，默认为 'pool.ntp.org'
    """
    client = ntplib.NTPClient()
    try:
        response = client.request(ntp_server)
        timestamp = response.tx_time
        new_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
        # 执行命令来设置系统时间
        subprocess.run(['date', '-s', new_time], check=True)
        # 设置系统时间后，同步写入 RTC（UTC）
        sys_write_rtc()
        print(f"Time synchronized with NTP server {ntp_server}: {new_time}")
    except Exception as e:
        print(f"Failed to synchronize time with NTP server {ntp_server}: {e}")

def sync_time_with_ntp_fallback():
    """使用备用服务器的NTP同步"""
    for server in NTP_SERVERS:
        try:
            print(f"尝试连接NTP服务器: {server}")
            # 这里调用原有的同步逻辑，但使用不同的服务器
            result = sync_with_server(server)
            if result:
                print(f"时间同步成功，使用服务器: {server}")
                return True
        except Exception as e:
            print(f"服务器 {server} 同步失败: {e}")
            continue
    
    print("所有NTP服务器均无法连接")
    return False
    

def get_sys_time():
    #获取当前系统时间
    # current_time = subprocess.check_output("date")
    # print('当前系统时间：%s'%current_time)
    #  return current_time
    """
    获取当前系统时间
    返回:
        str: "YYYY-MM-DD HH:MM:SS" 格式的时间字符串 或 None (如果获取失败)
    """
    try:
        return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    except Exception as e:
        print(f"获取系统时间失败: {e}")
        return None
    


def get_rtc_time():
    """
    查看rtc时间并返回格式化的时间字符串
    return:
        str: "YYYY-MM-DD HH:MM:SS" 格式的时间字符串 或 None (如果获取失败)
    """
    return_cmd = subprocess.run('hwclock --show --utc', stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', shell=True)
    if return_cmd.returncode == 0:
        rtc_time_str = return_cmd.stdout.strip()
        # print('rtc时间:%s' % rtc_time_str)
        try:
            time_parts = []
            i = 0
            while i < len(rtc_time_str) - 1:
                if rtc_time_str[i].isdigit() and rtc_time_str[i+1] == ':':
                    # 找到了 H: 模式
                    hour = rtc_time_str[i:i+1] if i == 0 or not rtc_time_str[i-1].isdigit() else rtc_time_str[i-1:i+1]
                    if i+3 < len(rtc_time_str) and rtc_time_str[i+2:i+4].isdigit():
                        minute = rtc_time_str[i+2:i+4]
                        if i+5 < len(rtc_time_str) and rtc_time_str[i+4] == ':' and rtc_time_str[i+5:i+7].isdigit():
                            second = rtc_time_str[i+5:i+7]
                            time_parts = [hour.zfill(2), minute, second]
                            break
                elif rtc_time_str[i:i+2].isdigit() and i+2 < len(rtc_time_str) and rtc_time_str[i+2] == ':':
                    # 找到了 HH: 模式
                    hour = rtc_time_str[i:i+2]
                    if i+5 < len(rtc_time_str) and rtc_time_str[i+3:i+5].isdigit():
                        minute = rtc_time_str[i+3:i+5]
                        if i+6 < len(rtc_time_str) and rtc_time_str[i+5] == ':' and rtc_time_str[i+6:i+8].isdigit():
                            second = rtc_time_str[i+6:i+8]
                            time_parts = [hour, minute, second]
                            break
                i += 1
            if time_parts:
                # RTC 保存为 UTC，这里转换成本地时间字符串返回
                today_utc = datetime.datetime.utcnow()
                hour, minute, second = map(int, time_parts)
                dt_utc = today_utc.replace(hour=hour, minute=minute, second=second, microsecond=0)
                # 本地与UTC的偏移（包含夏令时等）
                tz_offset = datetime.datetime.now() - datetime.datetime.utcnow()
                local_dt = dt_utc + tz_offset
                formatted_time = local_dt.strftime("%Y-%m-%d %H:%M:%S")
                return formatted_time
            # 如果没有解析到具体时间，退回原有兜底逻辑  
            return rtc_time_str.replace('\n', '').strip()   
        except Exception as e:
            print(f"时间解析失败: {e}")
            return rtc_time_str.replace('\n', '').strip()
    else:
        print(f"获取RTC时间失败: {return_cmd.stderr}")
        return None


def set_rtc(new_time:str):
    """
    设置rtc时间
    new_time: 新的时间字符串，格式为 "YYYY-MM-DD HH:MM:SS"
    return:
        bool: True 表示设置成功,False 表示设置失败
    """
    #设置系统时间
    try:
        subprocess.check_call(["date", "-s", new_time])
        sys_write_rtc() 
        return True
    except Exception as e:
        print("the rtc set failed",e)
        return False
        
def sys_write_rtc():
    #系统时间同步到rtc
    try:
        result = os.system('hwclock -w --utc')
        if result == 0:
            return True
        else:
            print("the sys time sync to rtc failed")
            return False
    except Exception as e:
        print("the sys time get to rtc failed",e)
        return False


def rtc_write_sys():
    #rtc时间写入到系统（按 UTC 解释）
    try:
        result = os.system('hwclock -s --utc')
        if result == 0:
            return True
        else:
            print("rtc time sync to sys failed")
            return False
    except Exception as e:
        print("rtc write to sys failed", e)
        return False

def get_next_collection_time_with_time(interval_seconds):
    """
    根据设定的采集间隔和传入的时间字符串，计算下一个采集时间点
    参数:
    interval_seconds: 采集间隔（秒）
    current_time_str: 当前时间字符串，格式为 "YYYY-MM-DD HH:MM:SS"
    返回: next_time: 下一个采集时间点（秒）
            wait_seconds: 需要等待的秒数
    """
    
    # 支持的固定时间点（秒）
    supported_intervals = [1, 2, 4, 5, 10, 15, 20, 30, 60, 300, 600,
                            900, 1200, 1800, 3600, 5400, 7200, 10800]
    
    # 如果不是预定义的时间点，直接返回间隔时间
    if interval_seconds not in supported_intervals:
        return None, None

    data_t = get_sys_time()
    hour, minute, second = data_t[3], data_t[4], data_t[5]
    date_part, time_part = data_t.split(' ')
    hour, minute, second = map(int, time_part.split(':'))
    # 计算当前时间的总秒数（一天内）
    current_total_seconds = hour * 3600 + minute * 60 + second
    # 添加调试信息
    print("Debug - Current time: %02d:%02d:%02d (total: %d seconds)" % 
            (hour, minute, second, current_total_seconds))
    
    # 计算下一个采集时间点
    next_total_seconds = ((current_total_seconds // interval_seconds) + 1) * interval_seconds
    
    # 处理跨越午夜的情况
    if next_total_seconds >= 86400:  # 24 * 3600
        # 检查是否应该在00:00:00采集
        if next_total_seconds == 86400:
            # 正好在午夜采集
            wait_seconds = 86400 - current_total_seconds
            next_total_seconds = 0  # 表示第二天的00:00:00
        else:
            # 跨越到第二天的其他时间点
            next_total_seconds = next_total_seconds - 86400
            wait_seconds = (86400 - current_total_seconds) + next_total_seconds   
    else:
        # 计算需要等待的秒数
        wait_seconds = next_total_seconds - current_total_seconds
    if wait_seconds <= 0:
        wait_seconds = interval_seconds
        
    return next_total_seconds, wait_seconds






